package com.kingmed.kmss.bpmn.modules.backup.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kingmed.kmss.bpmn.flow.helper.HistoryHelper;
import com.kingmed.kmss.bpmn.flow.helper.ProcessHelper;
import com.kingmed.kmss.bpmn.flow.helper.TaskHelper;
import com.kingmed.kmss.bpmn.modules.backup.service.BizApprovalTrailService;
import com.kingmed.kmss.bpmn.flow.service.base.BpmCustomServiceImpl;
import com.kingmed.kmss.bpmn.flow.service.msg.BpmnMsgServiceImpl;
import com.kingmed.kmss.common.bo.bpmn.ProcessVariableBO;
import com.kingmed.kmss.common.bo.bpmn.TaskBO;
import com.kingmed.kmss.common.bo.bpmn.TaskExBO;
import com.kingmed.kmss.common.constant.bpmn.BpmnConstant;
import com.kingmed.kmss.common.constant.bpmn.ProcessConstant;
import com.kingmed.kmss.common.constant.marketing.MktConstants;
import com.kingmed.kmss.common.dto.admin.ums.LoginUserDTO;
import com.kingmed.kmss.common.exception.BusinessException;
import com.kingmed.kmss.common.qc.bpmn.MyTaskQC;
import com.kingmed.kmss.common.qc.bpmn.ProcessQueryCondition;
import com.kingmed.kmss.common.satoken.LoginHelper;
import com.kingmed.kmss.common.utils.MessageUtils;
import com.kingmed.kmss.common.utils.ProcessUtils;
import com.kingmed.kmss.common.utils.StringUtils;
import com.kingmed.kmss.common.vo.CommonPage;
import com.kingmed.kmss.common.vo.CommonResponse;
import com.kingmed.kmss.common.vo.CommonResponseHelper;
import com.kingmed.kmss.framework.feign.client.admin.CommonAdminFeignServiceFacade;
import com.kingmed.kmss.framework.feign.client.dict.DictFeignServiceFacade;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 需补充审批功能所需要的任务类接口，包括任务认领，任务执行（通过/驳回)，我的待办任务，我的已办任务等接口
 * </p>
 */
@RestController
@Slf4j
@RequestMapping("/ext")
@Api(tags = "bpmn-任务管理")
public class TaskController {

    @Autowired
    private BpmCustomServiceImpl bpmCustomService;

    @Autowired
    HistoryHelper historyHelper;

    @Autowired
    TaskHelper taskHelper;

    @Autowired
    ProcessHelper procHelper;

    @Autowired
    BizApprovalTrailService trailSvc;

    @Autowired
    CommonAdminFeignServiceFacade remoteAdminSvc;
    @Autowired
    DictFeignServiceFacade dictFeignSvc;
    @Autowired
    BpmnMsgServiceImpl msgSvc;

    /**
     * 前端没用到
     *
     * @param processId
     * @return
     */
    @ApiOperation("流程实例当前进行中任务")
    @RequestMapping(value = "/process/instance/tasks", method = RequestMethod.GET)
    public CommonResponse<?> getCurrByProcessId(@RequestParam("processId") String processId) {

        return CommonResponseHelper.success(bpmCustomService.getCurrTasksByProcInstId(processId));
    }

    /**
     * 1 前端用到
     *
     * @param param
     * @return
     */
    @ApiOperation("待我审批列表")
    @PostMapping(value = "/task/todo")
    public CommonResponse<CommonPage<TaskBO>> myTodo(@RequestBody MyTaskQC param) {

        if (StringUtils.isEmpty(param.getUserId())) {
            LoginUserDTO loginUser = LoginHelper.getLoginUser();

            if (loginUser == null || loginUser.getUsername() == null) {
                return CommonResponseHelper.fail(MessageUtils.message("userNotLoggedIn"));
            }
            param.setUserId(loginUser.getUsername());
            param.setCurrApprover(loginUser.getUsername());
        }

        Page<TaskBO> tasks = bpmCustomService.getTasksByUser(param.getUserId(), param.getBizType(), param.getPageNum(),
                param.getPageSize(), param.getStartDate(), param.getEndDate());
        if (tasks == null) return null;
        return CommonResponseHelper.success(CommonPage.restPage(tasks));
    }

    /**
     * 2前端用到
     *
     * @return
     */
    @ApiOperation("待我审批数量")
    @PostMapping(value = "/task/todoNum")
    public CommonResponse<Integer> myTodoNum() {
        MyTaskQC param = new MyTaskQC();
        if (StringUtils.isEmpty(param.getUserId())) {
            LoginUserDTO loginUser = LoginHelper.getLoginUser();

            if (loginUser == null || loginUser.getUsername() == null) {
                return CommonResponseHelper.fail(MessageUtils.message("userNotLoggedIn"));
            }
            param.setUserId(loginUser.getUsername());
            param.setCurrApprover(loginUser.getUsername());
        }

        Integer num = bpmCustomService.getTasksNumByUser(param.getUserId(), param.getBizType());
        return CommonResponseHelper.success(num);
    }

    /**
     * 前端没用到
     *
     * @param param
     * @return
     */
    @ApiOperation("流程实例任务列表")
    @PostMapping(value = "/process/tasks")
    public CommonResponse<?> processtasks(@RequestBody ProcessQueryCondition param) {

        List<TaskBO> tasks = bpmCustomService.processtasks(param.getInstanceId());
        return CommonResponseHelper.success(tasks);
    }

    /**
     * 前端没用到
     *
     * @param id
     * @return
     */
    @ApiOperation("根据TaskID认领任务")
    @RequestMapping(value = "/task/claim", method = RequestMethod.GET)
    public CommonResponse<?> claimTask(@RequestParam("id") String id) {
        TaskBO task = new TaskBO();
        bpmCustomService.claimTask(id, "test");
        return CommonResponseHelper.success(task);
    }

    /**
     * 前端没用到
     *
     * @param taskId
     * @return
     */
    @ApiOperation("根据TaskID获取用户任务")
    @PostMapping(value = "/task/{taskId}")
    public CommonResponse<?> findTaskById(@PathVariable String taskId) {
        TaskBO task = bpmCustomService.findTaskById(taskId);
        return CommonResponseHelper.success(task);
    }

    /**
     * 3前端用到
     *
     * @param taskExBO
     * @return
     */
    @ApiOperation("执行审批任务")
    @PostMapping(value = "/task/complete")
    public CommonResponse<List<TaskBO>> complete(@RequestBody TaskExBO taskExBO) {

        // 转换TaskExBO到TaskBO以保持内部逻辑
        TaskBO taskBO = new TaskBO();
        taskBO.setTaskId(taskExBO.getTaskId());

        Long userAdminId = 0L;
        if (StringUtils.isEmpty(taskExBO.getStartUserId())) {
            LoginUserDTO loginUser = LoginHelper.getLoginUser();

            if (loginUser == null || loginUser.getUsername() == null) {
                return CommonResponseHelper.fail(MessageUtils.message("userNotLoggedIn"));
            }
            taskExBO.setStartUserId(loginUser.getUsername());
            userAdminId = loginUser.getId();
        }

        String userId = taskExBO.getStartUserId();
        ProcessVariableBO procVar = new ProcessVariableBO();
        Map<String, Object> varMap = new HashMap<String, Object>();
        varMap.put(BpmnConstant.VarKeys.COMMENT, taskExBO.getComment());
        varMap.put(BpmnConstant.VarKeys.APPROVED, taskExBO.getApproved());
        if (StringUtils.isNotEmpty(taskExBO.getBizTitle())) {
            varMap.put(BpmnConstant.VarKeys.BIZ_TITLE, taskExBO.getBizTitle());
        }
        Map<String, String> bizTypeDict = dictFeignSvc.getSysDictMap(ProcessConstant.DictCode.PROCESS_BUSINESS_TYPE);
        String bizTypeName = bizTypeDict.get(taskExBO.getBizType());
        varMap.put(BpmnConstant.VarKeys.BIZ_TYPE_NAME, bizTypeName);
        procVar.setVarMap(varMap);
        taskBO.setProcVars(procVar);


        // 找到对应的task信息
        Task task = null;
        String procInstId = "";
        String userIdEx = taskExBO.getStartUserId();
        if (StringUtils.isEmpty(taskBO.getTaskId())) {
            String businessKey = ProcessUtils.generateBusinessKey(taskExBO.getBizType(), taskExBO.getBizId());

            if (StringUtils.isNotEmpty(userId)) {
                userIdEx = String.format("%%%s%%", userId);
            }
            List<Task> tasks = taskHelper.findTaskByBizKeyAndUser(businessKey, userIdEx);
            if (tasks == null || tasks.size() == 0) {
                throw new BusinessException("找不到任务: " + taskBO.getTaskId());
            }
            task = tasks.get(0);
        } else {
            task = taskHelper.findTaskById(taskBO.getTaskId());
        }

        if (task != null) {
            procInstId = task.getProcessInstanceId();
        } else {
            throw new BusinessException("找不到任务: " + taskBO.getTaskId());
        }

        if (StringUtils.isNotEmpty(task.getAssignee())
                && task.getAssignee().contains(MktConstants.LIST_STRING_SEPERATOR_2)) {
            bpmCustomService.unclaimTask(task.getId());
            bpmCustomService.claimTask(task.getId(), userId);
        }
        bpmCustomService.completeTask(task.getId(), taskBO.getProcVars().getVarMap());

        List<TaskBO> tasks = bpmCustomService.getCurrTasksByProcInstId(procInstId);

        try {
            msgSvc.markMsgAsRead(taskExBO.getBizType(), taskExBO.getBizId(), userAdminId);
        } catch (Exception e) {
            log.error("设置审批相关站内消息状态失败!");
        }
        return CommonResponseHelper.success(tasks);
    }
}
